/*
 * @Author: chenbolin@msn.cn
 * @Date: 2023-03-24 11:24:04
 * @LastEditors: chenbolin@msn.cn
 * @LastEditTime: 2023-10-12 14:37:16
 * @FilePath: \multifunctional\src\App\wireless\ChannelScan.c
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
#include "ChannelScan.h"
#include "Sys.h"

#define MHz(x) (x * 1000000)

typedef struct
{
    bool start;
    uint8_t ch;
    uint8_t count;
    SysTime_t lastTime;
} ChannelScan_t;

static int CHANNEL_TABLE[CHANNEL_SCAN_CHANNEL_COUNT] = {//477\480\483\486\489\492\495\498\501\504
    MHz(477),
    MHz(480),
    MHz(483),
    MHz(486),
    MHz(489),
    MHz(492),
    MHz(495),
    MHz(498),
    MHz(501),
    MHz(504)};

static ChannelScan_t gChScan;
static ChannelScanSet_f g_setChannel = NULL;

bool ChannelScanIsStart(void)
{
    return gChScan.start;
}

void ChannelScanStop(void)
{
    gChScan.start = 0;
}

void ChannelScanStart(uint8_t ch)
{
    gChScan.start = true;
    gChScan.ch = 0;
    gChScan.count = 0;
    if(g_setChannel)
    {
        g_setChannel(ch, CHANNEL_TABLE[ch]);
    }

    gChScan.lastTime = SysTime();
}

void ChannelScanPoll(void)
{
    ChannelScan_t *ql = &gChScan;
    uint8_t ch;

    if (ql->start)
    {
        if (ql->lastTime == 0 || SysTimeHasPast(ql->lastTime, 1000))
        {
            if (ql->count % 2)
            {
                ch = ql->ch + CHANNEL_SCAN_CHANNEL_COUNT / 2;
                ql->ch++;
            }
            else
            {
                ch = ql->ch;
            }
            
            if(g_setChannel)
            {
                g_setChannel(ch, CHANNEL_TABLE[ch]);
            }
            
            ql->count++;
            if (ql->count >= CHANNEL_SCAN_CHANNEL_COUNT)
            {
                ql->ch = 0;
                ql->count = 0;
            }
            ql->lastTime = SysTime();
        }
    }
}

void ChannelScanInitialize(ChannelScanSet_f setChannel)
{
    g_setChannel = setChannel;
}
